<template>
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>奖励规则管理</p>
    </header>
    <div class="content">
      <div class="section">
        <div class="section-title">
          <span>活跃规则</span>
          <div class="action-buttons">
            <button class="init-btn" @click="initDefaultRules">
              <i class="fa fa-magic"></i> 初始化默认规则
            </button>
            <button class="add-btn" @click="showCreateForm = true">
              <i class="fa fa-plus"></i> 新增规则
            </button>
          </div>
        </div>
        <div v-if="activeRules.length === 0" class="empty">暂无活跃规则</div>
        <div v-else class="rules-list">
          <div v-for="rule in activeRules" :key="rule.id" class="rule-item">
            <div class="rule-info">
              <div class="rule-name">{{ rule.ruleName }}</div>
              <div class="rule-desc">
                <span v-if="rule.ruleType === 'DEPOSIT'">
                  充值满 ¥{{ formatAmount(rule.conditionValue) }} 赠送 ¥{{ formatAmount(rule.ruleValue) }}
                </span>
                <span v-else-if="rule.ruleType === 'WITHDRAW'">
                  提现手续费 {{ (rule.ruleValue * 100).toFixed(1) }}%
                </span>
              </div>
            </div>
            <div class="rule-actions">
              <button class="action-btn disable" @click="toggleRule(rule, false)">
                <i class="fa fa-pause"></i> 禁用
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 创建规则表单 -->
      <div v-if="showCreateForm" class="modal-overlay" @click="showCreateForm = false">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h3>创建奖励规则</h3>
            <button class="close-btn" @click="showCreateForm = false">
              <i class="fa fa-times"></i>
            </button>
          </div>
          <form @submit.prevent="createRule" class="rule-form">
            <div class="form-group">
              <label>规则类型</label>
              <select v-model="newRule.ruleType" required>
                <option value="DEPOSIT">充值奖励</option>
                <option value="WITHDRAW">提现手续费</option>
              </select>
            </div>
            <div class="form-group">
              <label>规则名称</label>
              <input type="text" v-model="newRule.ruleName" placeholder="请输入规则名称" required />
            </div>
            <div v-if="newRule.ruleType === 'DEPOSIT'" class="form-group">
              <label>充值条件 (元)</label>
              <input type="number" v-model.number="newRule.conditionValue" placeholder="充值满多少元" step="0.01" required />
            </div>
            <div class="form-group">
              <label v-if="newRule.ruleType === 'DEPOSIT'">奖励金额 (元)</label>
              <label v-else>手续费率 (%)</label>
              <input type="number" v-model.number="newRule.ruleValue" :placeholder="newRule.ruleType === 'DEPOSIT' ? '赠送多少元' : '手续费百分比'" :step="newRule.ruleType === 'DEPOSIT' ? '0.01' : '0.1'" required />
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showCreateForm = false">取消</button>
              <button type="submit" class="submit-btn">创建</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import Footer from '../components/Footer.vue'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { walletApi } from '../api'

const router = useRouter()
const activeRules = ref([])
const showCreateForm = ref(false)
const newRule = ref({
  ruleType: 'DEPOSIT',
  ruleName: '',
  conditionValue: null,
  ruleValue: null
})

const loadActiveRules = async () => {
  try {
    activeRules.value = await walletApi.getActiveRules()
  } catch (e) {
    console.error('加载活跃规则失败:', e)
  }
}

const initDefaultRules = async () => {
  try {
    // 检查是否已有规则
    const existingRules = await walletApi.getActiveRules()
    const hasDepositRule = existingRules.some(r => r.ruleType === 'DEPOSIT' && r.conditionValue === 100)
    const hasWithdrawRule = existingRules.some(r => r.ruleType === 'WITHDRAW')

    // 创建充值奖励规则：每充值100元赠送10元
    if (!hasDepositRule) {
      await walletApi.createRewardRule({
        ruleType: 'DEPOSIT',
        ruleName: '充值满100元赠送10元',
        conditionValue: 100,
        ruleValue: 10,
        isActive: true
      })
    }

    // 创建提现手续费规则：10%手续费
    if (!hasWithdrawRule) {
      await walletApi.createRewardRule({
        ruleType: 'WITHDRAW',
        ruleName: '提现手续费10%',
        conditionValue: null,
        ruleValue: 0.1, // 10% = 0.1
        isActive: true
      })
    }

    alert('默认规则初始化成功！')
    await loadActiveRules()
  } catch (e) {
    alert('初始化规则失败: ' + e.message)
  }
}

const createRule = async () => {
  try {
    await walletApi.createRewardRule(newRule.value)
    showCreateForm.value = false
    newRule.value = {
      ruleType: 'DEPOSIT',
      ruleName: '',
      conditionValue: null,
      ruleValue: null
    }
    await loadActiveRules()
  } catch (e) {
    alert('创建规则失败: ' + e.message)
  }
}

const toggleRule = async (rule, enable) => {
  try {
    if (enable) {
      await walletApi.enableRule(rule.id)
    } else {
      await walletApi.disableRule(rule.id)
    }
    await loadActiveRules()
  } catch (e) {
    alert('操作失败: ' + e.message)
  }
}

const formatAmount = v => Number(v || 0).toFixed(2)
const goBack = () => router.push('/wallet')

onMounted(() => {
  loadActiveRules()
})
</script>

<style scoped>
.wrapper { width: 100%; min-height: 100%; }
header { width: 100%; height: 12vw; background-color: #0097ff; color: #fff; font-size: 4.8vw; position: fixed; left: 0; top: 0; z-index: 1000; display: flex; justify-content: center; align-items: center; }
header i { position: absolute; left: 3vw; font-size: 6vw; color: #fff; cursor: pointer; }
.content { margin-top: 14vw; padding: 4vw; }
.section { margin-bottom: 6vw; }
.section-title { display: flex; justify-content: space-between; align-items: center; font-size: 4.4vw; font-weight: 600; margin-bottom: 3vw; }
.action-buttons { display: flex; gap: 2vw; }
.add-btn, .init-btn { height: 8vw; border: none; border-radius: 1.5vw; padding: 0 4vw; color: #fff; font-size: 3.6vw; display: flex; align-items: center; gap: 2vw; }
.add-btn { background: #38ca73; }
.init-btn { background: #0097ff; }
.add-btn i, .init-btn i { font-size: 3.2vw; }
.empty { padding: 6vw; text-align: center; color: #999; font-size: 3.8vw; }
.rules-list { display: flex; flex-direction: column; gap: 3vw; }
.rule-item { background: #fff; border-radius: 2vw; padding: 4vw; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
.rule-info { margin-bottom: 3vw; }
.rule-name { font-size: 4.2vw; font-weight: 600; color: #333; margin-bottom: 2vw; }
.rule-desc { font-size: 3.8vw; color: #666; }
.rule-actions { display: flex; gap: 2vw; }
.action-btn { height: 7vw; border: none; border-radius: 1.5vw; padding: 0 3vw; font-size: 3.4vw; display: flex; align-items: center; gap: 1.5vw; }
.action-btn.disable { background: #ff6b35; color: #fff; }
.action-btn.disable:hover { background: #e55a2b; }

/* 模态框样式 */
.modal-overlay { position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 2000; }
.modal-content { background: #fff; border-radius: 3vw; width: 90%; max-width: 400px; max-height: 80vh; overflow-y: auto; }
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 4vw; border-bottom: 1px solid #eee; }
.modal-header h3 { font-size: 4.4vw; font-weight: 600; margin: 0; }
.close-btn { border: none; background: none; font-size: 5vw; color: #999; cursor: pointer; }
.rule-form { padding: 4vw; }
.form-group { margin-bottom: 4vw; }
.form-group label { display: block; font-size: 3.8vw; color: #666; margin-bottom: 2vw; }
.form-group input, .form-group select { width: 100%; height: 10vw; border: 1px solid #ddd; border-radius: 2vw; padding: 0 3vw; font-size: 4vw; }
.form-actions { display: flex; gap: 3vw; margin-top: 4vw; }
.cancel-btn, .submit-btn { flex: 1; height: 10vw; border: none; border-radius: 2vw; font-size: 4vw; font-weight: 600; }
.cancel-btn { background: #f5f5f5; color: #666; }
.submit-btn { background: #38ca73; color: #fff; }
</style>
